// pages/self_tagging/self_tagging.js
const app = getApp(), core = require('../../utils/core'), util = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tags: [], //string[] 官方提供的选项
    selectedTags:[], //string[] 选中的标签, 包括自定义的
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOpenerEventChannel().on('dataTransfer', data => {
      let selectedTags = [];
      data.model.forEach(item=>selectedTags.push(item.name));
      this.setData({selectedTags});
      util.getResumePersonalTags(true).then(items=>{
        let tags = [];
        items.forEach(item=>tags.push(item.name));
        this.setData({tags});
      });
    });

  },

  bindToggleTag(event) {
    let tag = event.currentTarget.dataset.tag;
    let index = this.data.selectedTags.indexOf(tag);
    if(index===-1) {
      this.data.selectedTags.push(tag);
    }else {
      this.data.selectedTags.splice(index, 1);
    }
    this.setData({selectedTags: this.data.selectedTags});
  },

  bindTagInput(event) {
    let tag = event.detail.value.replace(/^[\s,，]*/,'');
    if(tag!=='' && /[\s,，]$/.test(tag)) {
      tag = tag.replace(/[\s,，]*$/,'');
      if(tag.length>8) {
        wx.showToast({title: '标签最长8个字符',icon:'none'});
        return tag.substr(0,8);
      }
      if(this.data.selectedTags.indexOf(tag)!==-1) {
        // 标签已在选中列表中， 清空输入啥也不干
        return "";
      }
      this.data.selectedTags.push(tag);
      this.setData({selectedTags: this.data.selectedTags});
      return "";
    }
  },

  bindSubmit() {
    core.post({
      url: 'xilujob.user/save_module',
      data: {tags:this.data.selectedTags, module:'personal_tag'},
      success: ret => {
        this.getOpenerEventChannel().emit('dataTransfer', {model: ret.data.model, complete_percent:ret.data.complete_percent});
        wx.navigateBack();
      },
    })
  },

});
